package com.example.cc.client.processor;

import com.example.cc.client.manager.GenericCacheManager;
import com.example.cc.client.service.ClientConfigService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;

import java.util.Map;

@RequiredArgsConstructor
@Slf4j
public class ConfigSyncEnvironmentPostProcessor implements EnvironmentPostProcessor {

    private final ClientConfigService configService;

    @Autowired
    private GenericCacheManager<String, Object> cacheManager;

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        syncConfiguration();
    }

    private void syncConfiguration() {
        try {
            Map<String, Object> configurations = configService.loadAppAllConfig();
            cacheManager.updateCache(configurations);
            log.info("Configuration synchronized successfully.");
        } catch (Exception e) {
            log.error("Failed to synchronize configurations.", e);
        }
    }
}
